<template>
  <div class="dashboard">
    <div class="dashboard-header">
      <h1>欢迎使用医学文献智能识别与检索系统</h1>
      <p>管理和检索您的医学文献，体验智能化的研究工具</p>
    </div>

    <!-- 统计卡片 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" :xs="12" :sm="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon primary">
              <el-icon size="40" color="white"><Document /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.totalLiterature }}</div>
              <div class="stats-label">总文献数</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6" :xs="12" :sm="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon success">
              <el-icon size="40" color="white"><Star /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.totalFavorites }}</div>
              <div class="stats-label">收藏文献</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6" :xs="12" :sm="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon warning">
              <el-icon size="40" color="white"><View /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.recognizedLiterature }}</div>
              <div class="stats-label">已识别文献</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6" :xs="12" :sm="6">
        <el-card class="stats-card" shadow="hover">
          <div class="stats-content">
            <div class="stats-icon danger">
              <el-icon size="40" color="white"><Clock /></el-icon>
            </div>
            <div class="stats-info">
              <div class="stats-number">{{ stats.pendingLiterature }}</div>
              <div class="stats-label">待处理文献</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 快速操作和图表 -->
    <el-row :gutter="20" class="main-content">
      <el-col :span="16" :xs="24" :sm="16">
        <el-card class="action-card">
          <template #header>
            <div class="card-header">
              <span>快速操作</span>
            </div>
          </template>
          <div class="quick-actions">
            <el-row :gutter="20">
              <el-col :span="8" :xs="24" :sm="8">
                <el-button 
                  type="primary" 
                  size="large" 
                  @click="goToUpload"
                  class="action-button"
                  round
                >
                  <el-icon><Upload /></el-icon>
                  <span>上传文献</span>
                </el-button>
              </el-col>
              <el-col :span="8" :xs="24" :sm="8">
                <el-button 
                  type="success" 
                  size="large" 
                  @click="goToList"
                  class="action-button"
                  round
                >
                  <el-icon><Search /></el-icon>
                  <span>浏览文献</span>
                </el-button>
              </el-col>
              <el-col :span="8" :xs="24" :sm="8">
                <el-button 
                  type="warning" 
                  size="large" 
                  @click="goToFavorites"
                  class="action-button"
                  round
                >
                  <el-icon><Star /></el-icon>
                  <span>我的收藏</span>
                </el-button>
              </el-col>
            </el-row>
          </div>
        </el-card>
        
        <!-- 图表区域 -->
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>文献统计趋势</span>
            </div>
          </template>
          <div ref="chartRef" class="chart-container"></div>
        </el-card>
      </el-col>
      
      <el-col :span="8" :xs="24" :sm="8">
        <el-card class="recent-card">
          <template #header>
            <div class="card-header">
              <span>最近上传</span>
            </div>
          </template>
          <div class="recent-literature">
            <div 
              v-for="item in recentLiterature" 
              :key="item.id"
              class="recent-item"
              @click="goToDetail(item.id)"
            >
              <div class="recent-title">{{ item.title }}</div>
              <div class="recent-meta">
                <span class="recent-author">{{ item.authors }}</span>
                <span class="recent-time">{{ formatTime(item.createTime) }}</span>
              </div>
            </div>
            <div v-if="recentLiterature.length === 0" class="empty-recent">
              <el-empty description="暂无最近上传的文献" :image-size="80" />
            </div>
          </div>
        </el-card>
        
        <!-- 热门搜索 -->
        <el-card class="hot-search-card">
          <template #header>
            <div class="card-header">
              <span>热门搜索</span>
            </div>
          </template>
          <div class="hot-keywords">
            <el-tag 
              v-for="(keyword, index) in hotKeywords" 
              :key="index"
              class="hot-keyword"
              type="primary"
              effect="dark"
              @click="searchByKeyword(keyword)"
            >
              {{ keyword }}
            </el-tag>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import * as echarts from 'echarts'
import { Document, Star, View, Clock, Upload, Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { literatureApi } from '@/api/literature'
import { searchApi } from '@/api/search'
import { visualizationApi } from '@/api/visualization'
import type { Literature, PageResult } from '@/api/literature'
import type { LiteratureTrendRequest, LiteratureTrendResponse, TrendItem } from '@/api/visualization'

const router = useRouter()

// 图表引用
const chartRef = ref<HTMLDivElement | null>(null)

// 统计数据
const stats = ref({
  totalLiterature: 0,
  totalFavorites: 0,
  recognizedLiterature: 0,
  pendingLiterature: 0
})

// 最近文献
const recentLiterature = ref<Literature[]>([])

// 热门关键词
const hotKeywords = ref<string[]>([])

// 图表实例
let chart: echarts.ECharts | null = null

// 定时器
let refreshTimer: number | null = null

// 初始化图表
const initChart = async () => {
  if (chartRef.value) {
    chart = echarts.init(chartRef.value)
    
    // 获取真实数据
    try {
      const request: LiteratureTrendRequest = {
        granularity: 'day',
        startDate: new Date(Date.now() - 6 * 24 * 60 * 60 * 1000).toISOString().split('T')[0], // 最近一周
        endDate: new Date().toISOString().split('T')[0]
      }
      
      // 调用趋势API获取真实数据
      const response: LiteratureTrendResponse = await visualizationApi.getLiteratureTrend(request)
      
      // 准备折线图数据
      const xAxisData = response.items.map((item: TrendItem) => item.timePoint)
      const seriesData = response.items.map((item: TrendItem) => item.count)
      
      chart.setOption({
        title: {
          text: '本周文献上传趋势',
          textStyle: {
            fontSize: 14,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: seriesData,
            type: 'line',
            smooth: true,
            areaStyle: {
              color: '#409eff'
            },
            lineStyle: {
              color: '#409eff'
            },
            itemStyle: {
              color: '#409eff'
            }
          }
        ]
      })
    } catch (error) {
      console.error('获取图表数据失败:', error)
      // 如果获取失败，使用模拟数据
      const xAxisData = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
      const seriesData = [120, 200, 150, 80, 70, 110, 130]
      
      chart.setOption({
        title: {
          text: '本周文献上传趋势',
          textStyle: {
            fontSize: 14,
            fontWeight: 'normal'
          }
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: xAxisData
        },
        yAxis: {
          type: 'value'
        },
        series: [
          {
            data: seriesData,
            type: 'line',
            smooth: true,
            areaStyle: {
              color: '#409eff'
            },
            lineStyle: {
              color: '#409eff'
            },
            itemStyle: {
              color: '#409eff'
            }
          }
        ]
      })
    }
    
    // 监听窗口大小变化
    window.addEventListener('resize', () => {
      chart?.resize()
    })
  }
}

// 获取统计数据
const fetchStats = async () => {
  try {
    // 获取总文献数
    const totalResponse: PageResult<Literature> = await literatureApi.getList({ size: 1 })
    stats.value.totalLiterature = totalResponse.total
    
    // 获取最近上传的文献
    const recentResponse: PageResult<Literature> = await literatureApi.getList({ 
      size: 5, 
      sortField: 'create_time', 
      sortOrder: 'desc' 
    })
    recentLiterature.value = recentResponse.records
    
    // 获取收藏文献数
    const favoriteResponse: PageResult<Literature> = await literatureApi.getFavorites({ size: 1 })
    stats.value.totalFavorites = favoriteResponse.total
    
    // 获取已识别文献数 (状态1改为状态2，因为我们修改了显示逻辑)
    const recognizedResponse: PageResult<Literature> = await literatureApi.getList({ 
      size: 1,
      recognitionStatus: 2  // 原本是1(识别中)，现在改为2(已识别)
    })
    stats.value.recognizedLiterature = recognizedResponse.total
    
    // 获取待处理文献数
    const pendingResponse: PageResult<Literature> = await literatureApi.getList({ 
      size: 1,
      recognitionStatus: 0  // 未识别
    })
    stats.value.pendingLiterature = pendingResponse.total
    
    // 获取热门搜索关键词
    try {
      hotKeywords.value = await searchApi.getHotKeywords()
    } catch (error) {
      console.warn('获取热门搜索关键词失败:', error)
      // 如果获取失败，使用默认关键词
      hotKeywords.value = [
        '癌症治疗',
        '基因编辑',
        '免疫疗法',
        '药物研发',
        '临床试验',
        '医学影像',
        '人工智能',
        '精准医疗'
      ]
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
    ElMessage.error('获取统计数据失败: ' + (error instanceof Error ? error.message : '系统异常，请稍后重试'))
  }
}

// 格式化时间
const formatTime = (time: string) => {
  if (!time) return '-'
  try {
    // 更健壮的日期解析方法
    const date = new Date(time)
    if (isNaN(date.getTime())) {
      // 尝试其他常见日期格式
      const isoDate = new Date(time.replace(' ', 'T'))
      if (isNaN(isoDate.getTime())) {
        return time // 如果所有方法都失败，返回原始字符串
      }
      return formatDate(isoDate)
    }
    return formatDate(date)
  } catch (e) {
    // 如果解析失败，尝试直接返回原始字符串
    return time || '-'
  }
}

const formatDate = (date: Date) => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  if (diff < 60000) { // 1分钟内
    return '刚刚'
  } else if (diff < 3600000) { // 1小时内
    return `${Math.floor(diff / 60000)}分钟前`
  } else if (diff < 86400000) { // 1天内
    return `${Math.floor(diff / 3600000)}小时前`
  } else {
    return date.toLocaleDateString('zh-CN')
  }
}

// 导航方法
const goToUpload = () => {
  router.push('/literature/upload')
}

const goToList = () => {
  router.push('/literature/list')
}

const goToFavorites = () => {
  router.push('/literature/favorites')
}

const goToDetail = (id: number) => {
  router.push(`/literature/detail/${id}`)
}

// 按关键词搜索
const searchByKeyword = (keyword: string) => {
  // 这里应该跳转到搜索页面并传递关键词
  console.log('搜索关键词:', keyword)
}

// 刷新所有数据
const refreshAllData = () => {
  fetchStats()
  initChart()
}

// 开始定时刷新
const startAutoRefresh = () => {
  // 每30秒刷新一次数据
  refreshTimer = window.setInterval(() => {
    refreshAllData()
  }, 30000)
}

// 停止定时刷新
const stopAutoRefresh = () => {
  if (refreshTimer) {
    window.clearInterval(refreshTimer)
    refreshTimer = null
  }
}

onMounted(() => {
  fetchStats()
  nextTick(() => {
    initChart()
  })
  
  // 开始定时刷新
  startAutoRefresh()
})

onUnmounted(() => {
  // 停止定时刷新
  stopAutoRefresh()
})
</script>

<style scoped>
.dashboard {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.dashboard-header {
  text-align: center;
  margin-bottom: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 40px 20px;
  border-radius: 10px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.dashboard-header h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
  font-weight: 500;
}

.dashboard-header p {
  margin: 0;
  font-size: 16px;
  opacity: 0.9;
}

.stats-row {
  margin-bottom: 30px;
}

.stats-card {
  height: 120px;
  border-radius: 10px;
  overflow: hidden;
  transition: transform 0.3s, box-shadow 0.3s;
}

.stats-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.1);
}

.stats-content {
  display: flex;
  align-items: center;
  height: 100%;
}

.stats-icon {
  width: 70px;
  height: 70px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20px;
  flex-shrink: 0;
}

.stats-icon.primary {
  background: linear-gradient(135deg, #409eff 0%, #66b1ff 100%);
}

.stats-icon.success {
  background: linear-gradient(135deg, #67c23a 0%, #85ce61 100%);
}

.stats-icon.warning {
  background: linear-gradient(135deg, #e6a23c 0%, #ebb563 100%);
}

.stats-icon.danger {
  background: linear-gradient(135deg, #f56c6c 0%, #f78989 100%);
}

.stats-info {
  flex: 1;
}

.stats-number {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
  line-height: 1;
}

.stats-label {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.main-content {
  margin-bottom: 30px;
}

.action-card, .chart-card, .recent-card, .hot-search-card {
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

.card-header {
  font-weight: bold;
  color: #303133;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-actions {
  padding: 20px 0;
}

.action-button {
  width: 100%;
  height: 50px;
  font-size: 16px;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.chart-container {
  height: 300px;
  width: 100%;
}

.recent-literature {
  max-height: 300px;
  overflow-y: auto;
}

.recent-item {
  padding: 15px 0;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
}

.recent-item:hover {
  background-color: #f5f7fa;
  margin: 0 -15px;
  padding-left: 15px;
  padding-right: 15px;
}

.recent-item:last-child {
  border-bottom: none;
}

.recent-title {
  font-size: 14px;
  color: #303133;
  margin-bottom: 5px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 500;
}

.recent-meta {
  display: flex;
  justify-content: space-between;
  font-size: 12px;
  color: #909399;
}

.recent-author {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.recent-time {
  flex-shrink: 0;
  margin-left: 10px;
}

.empty-recent {
  text-align: center;
  padding: 40px 0;
}

.hot-keywords {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  padding: 10px 0;
}

.hot-keyword {
  cursor: pointer;
  transition: transform 0.2s;
}

.hot-keyword:hover {
  transform: scale(1.05);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .dashboard {
    padding: 10px;
  }
  
  .stats-row .el-col {
    margin-bottom: 15px;
  }
  
  .main-content .el-col {
    margin-bottom: 15px;
  }
  
  .dashboard-header h1 {
    font-size: 24px;
  }
  
  .stats-number {
    font-size: 24px;
  }
  
  .action-button {
    margin-bottom: 10px;
  }
}
</style>